package com.b2s.scrumblr.kb.service;

import com.b2s.scrumblr.kb.base.BootstrapHtmlTemplate;
import com.b2s.scrumblr.kb.core.util.HtmlUtil;
import com.b2s.scrumblr.kb.core.util.ReflectUtil;
import com.b2s.scrumblr.kb.exception.ScrumblrFileException;
import com.b2s.scrumblr.kb.model.Article;
import com.b2s.scrumblr.kb.repository.ArticleRepository;
import org.apache.commons.io.FileUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.util.NamedList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.solr.core.query.Query;
import org.springframework.data.solr.core.query.SolrPageRequest;
import org.springframework.data.solr.core.query.result.HighlightEntry;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.NameList;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/8/10.
 */
@Service
public class ArticleSolrService {
    @Resource
    private SolrClient client;

    @Resource
    private ArticleRepository repository;

    @Resource
    private BootstrapHtmlTemplate template;

    @Transactional
    public void save(Article article, File file){
        LocalDateTime dateTime = LocalDateTime.now();
        article.setId(UUID.randomUUID().toString());
        article.setCreateTime(dateTime.toString());
        article.setActive(1);


        try {
            article.setContent(HtmlUtil.stripTag(article.getHtml()));
        } catch (IOException e) {
            throw new ScrumblrFileException("",e);
        }


        StringBuilder sb = new StringBuilder();
        sb.append("<h1 align='center'>").append(article.getTitle()).append("</h1>").append(article.getHtml());
        template.setBody(sb.toString());
        article.setHtml(template.html());

        System.out.println(article.getHtml());
        try {
            FileUtils.write(file, article.getHtml());
        } catch (IOException e) {
            throw new ScrumblrFileException("save html file failed:", e);
        }
        article.setHtml(file.getName());

        Article art = repository.save(article);
        System.out.println(art.getId());

    }

    HighlightPage<Article> findByContent(String key){
        Pageable pageable = new SolrPageRequest(0, 10);
        return repository.findByContent(key, pageable);
    }

    HighlightPage<Article> findByContentLike(String key){
        Pageable pageable = new SolrPageRequest(0, 10);
        return repository.findByContentLike(key, pageable);
    }

    Page<Article> findByContentContaining(String key){
        Pageable pageable = new SolrPageRequest(0, 10);
        return repository.findByContentContaining(key, pageable);
    }

    List<Article> find(String key){
        return repository.find(key);
    }

    public List<Article> findHighlight(String key) throws InvocationTargetException, IllegalAccessException {
        Pageable pageable = new SolrPageRequest(0, 10);
        HighlightPage<Article> highlightPage = repository.findHighlight(key, pageable);
        List<Article> articles = highlightPage.getContent();
        if(articles!= null && !articles.isEmpty()){
            for(Article article : articles){
                List<HighlightEntry.Highlight> highlights = highlightPage.getHighlights(article);
                if(highlights!= null &&!highlights.isEmpty()){
                    for(HighlightEntry.Highlight highlight : highlights){
                        String field = highlight.getField().getName();
                        ReflectUtil.setFieldValue(article, field, highlight.getSnipplets().get(0));
                        article.setHtml(article.getHtml());
                    }
                }
            }
        }
        return articles;
    }

    public List<Article> getMyArticles(String creator){
        return repository.findByCreator(creator);
    }

    void findT() throws IOException, SolrServerException {
        SolrQuery query = new SolrQuery();
        query.setQuery("*test*");
        query.setHighlight(true);
        query.addHighlightField("content");
        query.setHighlightSimplePre("<font color='red'>");
        query.setHighlightSimplePost("</font>");
        query.set("hl.highlightMultiTerm", "true");
        query.set("hl.useFastVectorHighlighter", true);
//        query.setHighlightFragsize(10);
//        query.setHighlightSnippets(3);

        System.out.println(query);
        System.out.println("**************************************");

        QueryResponse response = client.query(query);

        System.out.println(response);
        System.out.println("**************************************");
        NamedList namedList = (NamedList) response.getResponse().get("highlighting");

        System.out.println(namedList);
    }

    public void deleteById(String id){
        repository.deleteById(id);
    }
}
